package com.study.spring.pdfandexcel;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author
 * @date 2021年11月22日 22:13
 * @description
 */
@RestController
public class ExportController {



    @PostMapping("/exportPDF")
    public void exportPDF(HttpServletResponse response) throws UnsupportedEncodingException {
        //指定解析器
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        String filename = "test.pdf";//需要调整文件位置
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;fileName="
                + URLEncoder.encode(filename, "UTF-8"));


        OutputStream outputStream = null;
        PdfStamper pdfStamper = null;
        PdfReader pdfReader = null;

        try {
            outputStream = response.getOutputStream();

            //读入PDF表单
            pdfReader = new PdfReader(filename);

            //根据表单生成一个新的pdf
            pdfStamper = new PdfStamper(pdfReader, outputStream);

            //获取pdf表单
            AcroFields fields = pdfStamper.getAcroFields();

            BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",
                    BaseFont.IDENTITY_H, BaseFont.EMBEDDED);


            fields.addSubstitutionFont(font);

            Map<String, String> data = new HashMap<>();
            data.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")));
            data.put("lang", "Java");
            data.put("status", "1");


            for (String key : data.keySet()) {
                fields.setField(key, data.get(key));
            }

            pdfStamper.setFormFlattening(true);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                pdfStamper.close();
                pdfReader.close();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
